package com.sqx.modules.errand.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.cityInfo.entity.CityInfo;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.entity.Indent;
import com.sqx.modules.errand.entity.SysComplaint;
import com.sqx.modules.errand.entity.TrainingCenter;
import com.sqx.modules.errand.service.AdminService;
import com.sqx.modules.errand.service.ComplaintService;
import com.sqx.modules.errand.service.IndentService;
import com.sqx.modules.errand.service.UserInfoService;
import com.sqx.modules.errand.vo.IndentVo;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import com.sqx.modules.utils.excel.ExportExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/adminerrand")
@Api(value = "管理端", tags = {"管理端"})
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private ComplaintService complaintService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private IndentService indentService;
    @Autowired
    private CommonInfoService commonInfoService;


    @ApiOperation("数据中心")
    @GetMapping(value = "findDataCenter")
    public Result findDataCenter() {

        return adminService.findDataCenter();
    }

    @ApiOperation("用户筛选")
    @GetMapping(value = "selectUserStatistics")
    public Result selectUserStatistics(String date, String dateType) {

        return adminService.selectUserStatistics(date, dateType);
    }

    @ApiOperation("任务分析")
    @GetMapping(value = "taskAnalysis")
    public Result taskAnalysis(String dateType, String date, Integer page, Integer limit, String indentState,Long cityId) {

        return adminService.taskAnalysis(dateType, date, page, limit, indentState,cityId);
    }

    @ApiOperation("用户中心 用户列表")
    @GetMapping(value = "findAllUser")
    public Result findAllUser(Integer page, Integer limit, String phone, Integer userType, String platform, String nickName,
                              String invitationCode, Integer isAgent, Integer onLineFlag,String inviterCode) {

        return adminService.findAllUser(page, limit, phone, userType, platform, nickName, invitationCode, isAgent, onLineFlag,inviterCode);
    }

    @ApiOperation("用户中心 用户详情")
    @GetMapping(value = "findUserMessage")
    public Result findUserMessage(Long userId) {

        return adminService.findUserMessage(userId);
    }

    @ApiOperation("邀请码查用户id")
    @GetMapping(value = "selectUserId")
    public Result selectUserId(String invitationCode) {

        return userService.selectUserId(invitationCode);
    }

    @ApiOperation("修改用户状态")
    @PostMapping(value = "updateStatus")
    public Result updateState(Long userId, Integer status) {

        return adminService.updateState(userId, status);
    }

    @ApiOperation("获取该用户所有派单任务")
    @GetMapping(value = "findUserAddIndent")
    public Result findUserAddIndent(Long userId, Integer page, Integer limit) {

        return adminService.findUserAddIndent(userId, page, limit);
    }

    @ApiOperation("获取该用户所有接单任务")
    @GetMapping(value = "findUserReceivingIndent")
    public Result findUserReceivingIndent(Long userId, Integer page, Integer limit) {
        return adminService.findUserReceivingIndent(userId, page, limit);
    }

    @ApiOperation("获取该师傅未完成的订单")
    @GetMapping(value = "findWaitIndent")
    public Result findWaitIndent(Long userId, Integer page, Integer limit) {
        return Result.success().put("data", adminService.findWaitIndent(userId, page, limit));
    }

    //查看全部骑手申诉（条件查询）
    @ApiOperation("查看全部骑手申诉")
    @GetMapping(value = "findAllAppeal")
    public Result findAllAppeal(Integer page, Integer limit, SysComplaint complaint) {

        return Result.success().put("data", complaintService.findAllAppeal(page, limit,complaint));
    }

    @ApiOperation("查看用户实名认证信息")
    @GetMapping(value = "findCertification")
    public Result findCertification(Long userId) {

        return adminService.findCertification(userId);
    }

    @ApiOperation("查看充值明细")
    @GetMapping(value = "findTopUpMoney")
    public Result findTopUpMoney(Integer page, Integer limit, PayDetails payDetails, String startTime, String endTime) {

        return adminService.findTopUpMoney( page, limit,payDetails, startTime, endTime);
    }


    @ApiOperation("查看提现记录")
    @GetMapping(value = "findWithdrawMoney")
    public Result findWithdrawMoney(Long userId, Integer page, Integer limit) {

        return adminService.findWithdrawMoney(userId, page, limit);
    }

    @ApiOperation("任务中心 查看所有订单")
    @PostMapping(value = "findAllIndent")
    public Result findAllIndent(Integer page, Integer limit, String date, String dateType, IndentVo indentVo) {
        return Result.success().put("data", adminService.findAllIndent(page, limit, date, dateType, indentVo));
    }

    @ApiOperation("订单中心")
    @PostMapping(value = "IndentCenter")
    public Result IndentCenter(Integer page, Integer limit, String indentType, String indentNumber, String indentState, String phone, String date, String dateType, String startTime, String endTime, String parentName, String parentParentName) {

        return adminService.IndentCenter(page, limit, indentType, indentNumber, indentState, phone, date, dateType, startTime, endTime, parentName, parentParentName);
    }


    @ApiOperation("管理端修改订单状态")
    @PostMapping(value = "updateIndentState")
    public Result updateIndentState(String indentNumber, String indentState) {

        return adminService.updateIndentState(indentNumber, indentState);
    }

    @ApiOperation("查看所有实名认证待审核用户")
    @GetMapping(value = "findAllCertification")
    public Result findAllCertification(Integer page, Integer limit, String nickName, String phone, String checkCertification) {
        return adminService.findAllCertification(page, limit, nickName, phone, checkCertification);
    }

    @ApiOperation("实名认证审核")
    @PostMapping("checkCertification")
    public Result checkCertification(Long userId, String checkCertification, String checkCertificationMessage) {

        return adminService.checkCertification(userId, checkCertification, checkCertificationMessage);
    }

    @ApiOperation("修改实名认证")
    @PostMapping("/updateCertification")
    public Result updateCertification(@RequestBody UserEntity userEntity) {

        int count = userService.count(new QueryWrapper<UserEntity>().eq("phone", userEntity.getPhone()).ne("user_id", userEntity.getUserId()));
        if (count > 0) {
            return Result.error("当前号码已被使用");
        }
        userEntity.setUserType(2);
        userService.updateById(userEntity);
        return Result.success();
    }

    @ApiOperation("删除实名认证")
    @PostMapping("/deleteCertification")
    public Result deleteCertification(Long userId) {
        userService.deleteCertification(userId);
        return Result.success();
    }

    @ApiOperation("管理员下架订单")
    @PostMapping(value = "adminSoldOutIndent")
    public Result adminSoldOutIndent(String indentNumber) {

        return adminService.adminSoldOutIndent(indentNumber);
    }

    @ApiOperation("培训中心")
    @GetMapping(value = "adminTrainingCenter")
    public Result adminTrainingCenter(Integer page, Integer limit, String title, Integer type) {

        return Result.success().put("data", adminService.adminTrainingCenter(page, limit, title, type));
    }

    @ApiOperation("培训中心编辑")
    @PostMapping(value = "updateAdminTrainingCenter")
    public Result updateAdminTrainingCenter(@RequestBody TrainingCenter trainingCenter) {
        return adminService.updateAdminTrainingCenter(trainingCenter);
    }

    @ApiOperation("培训中心添加")
    @PostMapping(value = "addAdminTrainingCenter")
    public Result addAdminTrainingCenter(@RequestBody TrainingCenter trainingCenter) {

        return adminService.addAdminTrainingCenter(trainingCenter);
    }

    @ApiOperation("钱包明细")
    @GetMapping(value = "findUserMoneyDetails")
    public Result findUserMoneyDetails(Long userId, Integer page, Integer limit) {

        return adminService.findUserMoneyDetails(userId, page, limit);
    }

    @ApiOperation("平台收入")
    @GetMapping(value = "findplatformMoney")
    public Result findplatformMoney(String dateType, String date) {

        return adminService.findplatformMoney(dateType, date);
    }

    @ApiOperation("师傅收入统计 完成订单数统计")
    @GetMapping(value = "findIncome")
    public Result findIncome(Long userId, String date, String dateType, Integer page, Integer limit) {

        return adminService.findIncome(userId, date, dateType, page, limit);
    }

    @GetMapping(value = "selectUserFeedback")
    @ApiOperation("查看意见反馈")
    public Result selectUserFeedback(String userEmail, Integer page, Integer limit, Integer feedType) {

        return adminService.selectUserFeedback(userEmail, page, limit, feedType);
    }

    @ApiOperation("接单排行榜")
    @GetMapping(value = "rankingList")
    public Result rankingList(Integer page, Integer limit, String address, String date, String dateType) {

        return userInfoService.rankingList(page, limit, address, date, dateType);
    }

    @ApiOperation("订单分析")
    @GetMapping(value = "selectOrderByStatus")
    public Result selectOrderByStatus(String date, String dateType,Long cityId) {

        return adminService.selectOrderByStatus(date, dateType,cityId);
    }

    @ApiOperation("保证金管理")
    @GetMapping(value = "selectCashDeposit")
    public Result selectCashDeposit(String phone, Integer type, Integer page, Integer limit, Long userId) {

        return adminService.selectCashDeposit(phone, type, page, limit, userId);
    }

    @ApiOperation("修改用户保证金")
    @GetMapping(value = "updateCashDeposit")
    public Result updateCashDeposit(Long userId, BigDecimal money, Integer type) {

        return userMoneyService.updateCashDeposit(userId, money, type);
    }

    @ApiOperation("转单")
    @PostMapping("/transferOfOrder")
    public Result transferOfOrder(Long indentId, Long riderUserId) {
        Indent indent = indentService.getById(indentId);
        if (indent.getRiderUserId() == null) {
            return Result.error("当前订单暂未有人接单");
        }
        int count = indentService.count(new QueryWrapper<Indent>().eq("rider_user_id", riderUserId).in("indent_state", 1, 2));
        if (count > 0) {
            return Result.error("当前师傅有暂未完成的订单");
        }
        UserEntity userEntity = userService.selectUserById(riderUserId);
        if (userEntity.getOnLineFlag()!=1){
            return Result.error("师傅未上线");
        }
        CommonInfo one1 = commonInfoService.findOne(261);
        Double cashDeposit = Double.parseDouble(one1.getValue());
        if (userEntity.getCashDeposit().doubleValue() < cashDeposit) {
            return Result.error("师傅保证金不足！");
        }
        if (!"1".equals(userEntity.getCheckCertification())) {
            return Result.error("师傅未进行实名认证！");
        }
        int minScore = Integer.parseInt(commonInfoService.findOne(365).getValue());
        if (userEntity.getCreditScore()<minScore){
            return Result.error("对方信用分不足");
        }
        if (userEntity.getUserId().equals(indent.getRiderUserId())) {
            return Result.error("不能选择相同的师傅！");
        }
        indent.setRiderUserId(riderUserId);
        indent.setIsTransfer(1);
        indentService.updateById(indent);
        UserEntity user = userService.getById(indent.getUserId());
        CommonInfo one = commonInfoService.findOne(307);
        List<String> msgList = new ArrayList<>();
        msgList.add(0, indent.getIndentNumber());
        if (indent.getIndentState() == 1) {
            msgList.add(1, "已接单");
        } else if (indent.getIndentState() == 4) {
            msgList.add(1, "已取货");
        } else {
            msgList.add(1, "进行中");
        }
        msgList.add(2, "师傅已更换，新师傅将尽快为您送达");
        msgList.add(3, DateUtils.format(new Date()));
        if (StringUtils.isNotEmpty(user.getOpenId())) {
            SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 3);
        }
        if (StringUtils.isNotEmpty(user.getClientid())) {
            userService.pushToSingle("更换师傅", "师傅已更换，新师傅将尽快为您送达", user.getClientid());
        }
        return Result.success();
    }

    @PostMapping("/distributionOrder")
    @ApiOperation("派单")
    public Result distributionOrder(Long indentId, Long userId) {
        return indentService.distributionOrder(indentId, userId);
    }

    @PostMapping(value = "riderStartDrive")
    @ApiOperation("开始服务")
    public Result riderStartDrive(Long userId, Long indentId) {
        return indentService.riderStartDrive(userId, indentId);
    }

    //师傅已送达
    @PostMapping(value = "riderDelivery")
    @ApiOperation("师傅完成订单")
    public Result riderDelivery(Long userId, String indentId) {

        return indentService.riderDelivery(userId, indentId);
    }

    @PostMapping(value = "riderCancelIndent")
    @ApiOperation("师傅取消订单")
    public Result riderCancelIndent(Long userId, String indentId) {

        return indentService.riderCancelIndent(userId, indentId);
    }

}
